<?php

namespace app\api\controller;

use app\common\model\Ad;
use app\common\model\Base;
use app\common\model\CapitalLog;
use app\common\controller\Api;
use app\common\model\CouponCollectRecord;
use app\common\model\FundsRecord;
use app\common\model\TaobaoConfig;
use app\common\model\TaobaoCoupon;
use app\common\model\TaobaoFunc;
use think\Db;
use think\Exception;
use think\exception\ErrorException;
use think\Cache;
use think\Request;

/**
 * 淘宝客php接口
 * @author Administrator
 *
 */

class Tbao extends Api
{

    protected $noNeedLogin=['test','taobao_index', 'taobao_item_coupon'];
    protected $noNeedRight = ['*'];
    protected $inputs;

    protected static $expire = null;

    public function __construct(Request $request = null){
        parent::__construct($request);
        $this->inputs = $this->request->request();
        $tbk_expire = Cache::get('tbk_expire','');
        if(!$tbk_expire)
        {
            self::clearCache();
        }
    }
    private $taobao_appkey=['24703018','24751961'],
            $taobao_appsecret=['69f271db4adf88ad166fe06e21dc4b09','2a1805383c2c28ff880e16e1b353b8fd'],
            $taobao_adzoneid=['156126650','179314415'];
    private $taobao_offset = 0;
    private $taobao_config;
    private $eUidBidArr=['xc'];


    /**
     * 好券清单API【导购】
	 * @param $top
	 * @param $adZoneId mm_xxx_xxx_xxx的第三位
	 * @param int $platForm 1：PC，2：无线，默认：1
	 * @param string $q 查询词
	 * @param string $cat 后台类目ID，用,分割，最大10个，该ID可以通过taobao.itemcats.get接口获取到
	 * @param int $page_no 第几页，默认：1（当后台类目和查询词均不指定的时候，最多出10000个结果，即page_no*page_size不能超过10000；当指定类目或关键词的时候，则最多出100个结果）
	 * @param int $page_size/最大100，否则淘宝获获取默认20
	 * @return false|mixed|string
	 */
    public function getDgItemCoupon($top,$adZoneId, $platForm=2, $q='' , $cat='' , $page_no= 1 , $page_size = 20){

        $req = load_tbk_req('TbkDgItemCouponGet',$adZoneId,$platForm);
        $req->setCat($cat);
        $req->setPageSize($page_size);
        $req->setQ($q);
        $req->setPageNo($page_no);
        $resp = $top->execute($req);
        return self::returnFormat($resp , 'results,tbk_coupon');
    }

    /**
     * 阿里妈妈推广券信息查询
     * @param \TopClient $top
     * @param string $me
     * @param string $itemId
     * @param string $activityId
     * @return mixed|string
     */
    public function getTbkCoupon($top,$me='' , $itemId ='' , $activityId = ''){
        if($me || $itemId || $activityId){
            $req = load_tbk_req('TbkCouponGet');
            $me && $req->setMe($me);
            $itemId && $req->setItemId($itemId);
            $activityId && $req->setActivityId($activityId);
            $resp = $top->execute($req);
            return self::returnFormat($resp , 'tbk_coupon_get_response');
        }

    }

    public static function returnFormat($xml ,$keys = ''){
        $xml =  json_encode($xml);
        $xml = json_decode($xml , TRUE);
        if($keys){
            $keys = explode(',', $keys);
            foreach($keys as $k=>$v){
                isset($xml[$v]) && $xml = $xml[$v];
            }
        }
        return $xml;
    }

    public function test(){

        $tb = load_top('24703018','69f271db4adf88ad166fe06e21dc4b09');
//        $req = load_tbk_req('TbkDgItemCouponGet','156126650',2);
//        $res = $tb->execute($req);
//        $list = self::returnFormat($res,'results,tbk_coupon');
//        $req = load_tbk_req('TbkCouponGet');
//        $req->setMe('Tp6dHUe7ERIGQASttHIRqVgWROSJPm0Nk0K1S5%2FWSyHyi1aSyqbpmonyxSZXp4Mu2P356kJe9XPU8Tfc129ECps1ZZX0A1cpDfqEFBOhTcwRyfS9lbS6UA0npquaVbj%2Ftymm5TtsxcyQqbxTIKOSamPfrr0N2WBeD0L6ZZ%2F72J77J8FmRkgg%2BK1hbRgwYUOf');
//        $res = $tb->execute($req);
//        $info = self::returnFormat($res,'tbk_coupon_get_response');
        $req = load_tbk_req('TbkOrderGet');
        $res = $tb->execute($req);
        $order = self::returnFormat($res);
        $this->success("OK",$order);
    }
	
	/**
	 * 设置appkey信息
	 * @param null $bzinfo 客户端类型
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
    private function setAppkeyInfo($bzinfo=NULL){
        if(empty($bzinfo)){
        	$model = new TaobaoConfig();
            $configs = $model->select();
            $bzinfo = [];
            foreach ($configs as $config)
            {
                if(strtolower($config['pv'])=='android')
                {
                    $index = 0;
                }
                else
                {
                    $index = 1;
                }
                $bzinfo['taobao_appkey'][$index] = $config['taobao_appkey'];
                $bzinfo['taobao_appsecret'][$index] = $config['taobao_appsecret'];
                $bzinfo['taobao_adzoneid'][$index] = $config['taobao_adzoneid'];

                if(isset($config['taobao_q']) && !isset($bzinfo['taobao_q']))
                {
                    $bzinfo['taobao_q'] = $config['taobao_q'];
                }

                if(isset($config['taobao_cat']) && !isset($bzinfo['taobao_cat']))
                {
                    $bzinfo['taobao_cat'] = $config['taobao_cat'];
                }

                if(isset($config['taobao_sort']) && !isset($bzinfo['taobao_sort']))
                {
                    $bzinfo['taobao_sort'] = $config['taobao_sort'];
                }

                if(isset($config['taobao_coupon_amount']) && !isset($bzinfo['taobao_coupon_amount']))
                {
                    $bzinfo['taobao_coupon_amount'] = $config['taobao_coupon_amount'];
                }

                if(isset($config['taobao_convert_msg']) && !isset($bzinfo['taobao_convert_msg']))
                {
                    $bzinfo['taobao_convert_msg'] = $config['taobao_convert_msg'];
                }

            }
        }
        $this->taobao_config = $bzinfo;
        if(isset($bzinfo['taobao_appkey']) && $bzinfo['taobao_appkey'] && !in_array($bzinfo['taobao_appkey'], ['',','])){
            foreach(['taobao_appkey' , 'taobao_appsecret' , 'taobao_adzoneid'] as $k=>$v){
                $this->{$v} = $bzinfo[$v];
            }
        }
    }
    /**
     * 淘宝客首页
     */
    public function taobao_index(){
        $pv = input('mobileType');
	    $page = input('post.page', 1, 'intval');
	    
        $this->setAppkeyInfo();
        
        //商品分类
        $returnData['category'] = Db::name('taobaoFunc')
	        ->select();
	
	    $time = time();
	    $where = [
		    'ai.position' => 5,
		    'ai.begin_time' => ['elt', $time],
		    'ai.end_time' => ['egt', $time],
	    ];
	    
	    //轮播图
        $returnData['banner'] = $indexAds = Db::name('appIndex')->alias('ai')
	        ->join('appClass ac', 'ai.app_class_id = ac.id', 'left')
	        ->where($where)
	        ->field('ai.position, ai.app_image, ai.name, ai.url, ai.param_id, ai.login, ac.ios_class, ac.android_class')
	        ->order(['ai.sort' => 'ASC'])
	        ->select();
        
        $returnData['coupon_list'] = $this->taobao_item_coupon($this->taobao_config['taobao_q'] , '' , $this->taobao_config['taobao_sort'] , $page , 20 , $pv , TRUE);
        
        $this->success("OK",$returnData);
    }
    /**
     * 获取淘宝客优惠券信息
	 * @param string $q 搜索关键字
	 * @param string $cat 分类
	 * @param string $sort 排序
	 * @param int $page_no 页数
	 * @param int $page_size 每页数量
	 * @param string $pv
	 * @param bool $return
	 * @return bool|false|null|\PDOStatement|string|\think\Collection
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
    public function taobao_item_coupon( $q = '' , $cat = '' , $sort = 'zk_final_price_asc' , $page_no=1 , $page_size=20 ,$pv='' ,$return = FALSE){
        $pv = $pv ? $pv : input('mobileType');
        if(strtolower($pv)=='ios'){
            $this->taobao_offset = 1;
        }
        if($q){
            $q = urldecode($q);
        }
        $this->setAppkeyInfo();
        $appkey_adzone = $this->taobao_appkey[$this->taobao_offset].$this->taobao_adzoneid[$this->taobao_offset];
        //查找数据库数量
        $count = TaobaoCoupon::number(['appkey_adzone'=>$appkey_adzone , 'q'=>$q]);
        $order = preg_replace('/^(.+)_(\w+)$/is','\\1 \\2',trim($sort));
        $whereMap =  ['appkey_adzone'=>$appkey_adzone] ;
        
        
        if($q){
            $whereMap['q'] = $q;
        }
        
        //数量大于5000从数据库获取，否则对接接口
        $list = $count>5000 ? TaobaoCoupon::search($whereMap ,['order_by'=>$order,'page'=>['num'=>$page_no,'size'=>$page_size]]) : NULL;
        
        
        if(empty($list)){
            $tb = load_top($this->taobao_appkey[$this->taobao_offset],$this->taobao_appsecret[$this->taobao_offset]);
            $newlist = self::getDgItemCoupon($tb, $this->taobao_adzoneid[$this->taobao_offset],2, $q , $cat , $page_no , $page_size);
            //dump($newlist);die;
            if($newlist){
                foreach($newlist as $k=>$v){
                	//如果有优惠券，匹配优惠券金额
                    if(isset($v['coupon_info']) && $v['coupon_info']){
                        preg_match('/(?P<start>\d+).\D+(?P<amount>\d+)/is', $v['coupon_info'] , $r);
                        $v['coupon_amount'] = isset($r['amount']) ? sprintf('%.2f', $r['amount'])  : 0;
                        $v['coupon_start_fee'] = isset($r['start']) ? sprintf('%.2f', $r['start'])  : 0;
                    }else{
                        continue;
                    }
                    $perc = isset($this->taobao_config['taobao_coupon_amount']) ? $this->taobao_config['taobao_coupon_amount'] : 1;
                    $v['me_alert'] = sprintf($this->taobao_config['taobao_convert_msg'] , sprintf('%.2f',$v['coupon_amount']*$perc) , $v['coupon_amount']);
                    
                    $url=parse_url($v['coupon_click_url']);
                    if($url['query']){
                        parse_str($url['query'] , $argvs);
                        $v['me'] = isset($argvs['e']) ? $argvs['e'] : '';
                    }
                    $v['small_images'] = json_encode(isset($v['small_images']) && $v['small_images'] ? $v['small_images'] : []);
                    $v['appkey_adzone'] = $appkey_adzone;
                    $v['item_description'] = is_array($v['item_description']) ? implode('', $v['item_description']) : $v['item_description'] ;
                
                    if($q){
                        $v['q'] = $q;
                    }
                    
                    if(!TaobaoCoupon::number(['num_iid'=>$v['num_iid'] , 'appkey_adzone'=>$v['appkey_adzone']])){
                        TaobaoCoupon::add($v);
                    }
                 
                }
            }
        }
	    
        if(empty($list)){
            $list = Db::name('taobaoCoupon')->where($whereMap)->order($order)->page($page_no, $page_size)->select();
        }
        
        if($list){
            foreach($list as $k=>$v){
                $list[$k]['small_images'] = json_decode($v['small_images'], true);
            }
        }
        if($return){
            return $list;
        }
        $this->success("OK",$list);
    }
    
    
    /**
     * 兑换优惠券信息
     * @param string $user_id
     * @param string $me
     * @param string $pv
     * @return array
     */
    public function taobao_coupon_info($user_id , $me , $pv=''){
        $pv = $pv ? $pv : input('mobileType');
        $uid = $user_id;
        if(strtolower($pv)=='ios'){
            $this->taobao_offset = 1;
        }
        $this->setAppkeyInfo();
        $tb = load_top($this->taobao_appkey[$this->taobao_offset],$this->taobao_appsecret[$this->taobao_offset]);
        $data = self::getTbkCoupon($tb,$me);
        return isset($data['data']) ? $data['data'] : [];
    }
    
    
    /**
     * 领券操作
     */
    public function taobao_coupon_convert(){
    	$me = input('post.me');
        $pv = input('post.mobileType', 'ios');
        $itemUrl = input('post.item_url');
        if(!$me || !$itemUrl) {
        	$this->error('参数错误');
        }
	
        $arr = parse_url($itemUrl);
        $params = $arr['query'];
        $paramsArr = explode('=', $params);
        if(isset($paramsArr['0']) && $paramsArr['0'] == 'id' && isset($paramsArr[1]) && !empty($paramsArr[1])) {
        	$goodsId = $paramsArr[1];
        } else {
        	$this->error('itemUrl格式错误');
        }
        
	    $uid = $this->auth->id;
        $userInfo = Db::name('user')->find($uid);
        $me = input("me",$me);
        $coupon_info = $this->taobao_coupon_info($uid , $me, $pv);
        if(!$coupon_info){
            $this->error('优惠券不存在');
        }
        if(!$coupon_info['coupon_total_count']){
            $this->error('优惠券已失效');
        }
        $perc = $this->taobao_config['taobao_coupon_amount'];
        if($perc<0){
            $this->error('扣优惠券不能为负数');
        }
        if($perc>0){
            //添加优惠券流水
            $leftMoney = intval($userInfo['voucher_balance']-$coupon_info['coupon_amount']*$perc);
            if($leftMoney<0){
                $leftMsg = sprintf('优惠券扣优惠券%s,当前优惠券:%s,优惠券不足' , $coupon_info['coupon_amount']*$perc,$userInfo['voucher_balance']);
                $this->error($leftMsg);
            }
            Db::startTrans();
            try{
                $totalAmount = $coupon_info['coupon_amount'] * $perc;
                $userRes = Db::name('user')->where(['id' => $uid])->setDec('voucher_balance', $totalAmount);
                if(!$userRes)
                {
                    throw new Exception('扣除优惠券出错');
                }
                
                $logModel = new FundsRecord();
                $res = $logModel->addRecord($uid, $totalAmount,$userInfo['voucher_balance'],$logModel::ACCOUNT_TYPE_VOUCHER, $logModel::OPE_TYPE_LESS, $logModel::TYPE_VOUCHER_EXCHANGE,'','兑换淘宝客优惠券');
                if(!$res)
                {
                    throw new Exception('添加兑换流水出错');
                }
                
                //添加用户领券记录
                $recordRes = Db::name('CouponCollectRecord')
	                ->insert([
		                'user_id' => $uid,
		                'goods_id' => $goodsId,
		                'create_time' => time()
	                ]);
                if(!$recordRes) {
                	throw new Exception('添加领取记录出错');
                }
	            
                Db::commit();
                $this->success('兑换成功');
            }
            catch (Exception $e)
            {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
    }
    /**
     * 一天清除一次优惠券的记录
     */
    public static function clearCache(){
        TaobaoCoupon::clear();
        self::$expire = strtotime(date("Ymd000000",strtotime("+1 day")))-time();
        Cache::set("tbk_expire",'1',self::$expire);
    }

}


